import { Component, Injector, OnDestroy, OnInit } from '@angular/core';
import { ConfigModule } from 'src/app/config.module';
import { Router } from '@angular/router';
import { Subject, Subscription } from 'rxjs';
import { listAnimation } from '../../../../animations/list.animation';
import { BaseUI } from '../../../../common/base';
import { NzTreeNodeOptions } from 'ng-zorro-antd/core/tree/nz-tree-base-node';
import { CacheService } from '../../cache/service/cache.service';


@Component({
    selector: 'app-cache-list',
    templateUrl: './index.component.html',
    styleUrls: ['./index.component.scss'],
    animations: [listAnimation],
})
export class CacheListComponent extends BaseUI implements OnInit, OnDestroy {
    router$: Subscription;
    onDestroy$: Subject<any> = new Subject<any>();
    private selectCacheKey = '';
    constructor(
        public _config: ConfigModule,
        private _router: Router,
        private _injector: Injector,
        public mainService: CacheService,
    ) {
        super(_injector);
    }

    ngOnInit() {
        this.listKey();
    }

    listKey(){
        this.loadingOne = true;
        this.mainService.getNames().subscribe(res => {
            if (res.code === 200){
                this.treeData = this.convertTreeToList(res.data);
            }
        }).add(()=>{this.loadingOne = false})
    }

    convertTreeToList(data:any[]): Array<NzTreeNodeOptions> {
        if (!data) return;
        let treeData: NzTreeNodeOptions[] = [];
        data.forEach(node => {
            let treeNode: NzTreeNodeOptions={} as NzTreeNodeOptions;
            treeNode.title = node.remark+"("+node.cacheName+")";
            treeNode.expanded = true;
            treeNode.key = node.cacheName;
            treeNode.isLeaf = true;
            treeData.push(treeNode);
        })
        return treeData
    }

    ngOnDestroy() {
        this.onDestroy$.complete();
    }


    /**
     * 部门树相关变量
     */
    treeData: any =[];
    listValue: any=[];
    cache: any={};
    loadingOne = false;
    loadingTwo = false;
    loadingThree = false;
    selectedTreeNode(key: string){
        this.loadingTwo = true;
        this.selectCacheKey = key;
        this.mainService.getKeys(key).subscribe(res=>{
            this.listValue = res.data;
        }).add(()=>{this.loadingTwo = false});
    }

    deleteCache(item: any) {
        this.mainService.clearCacheKey(item).subscribe().add(()=>{
            this.selectedTreeNode(this.selectCacheKey);
            if (this.selectCacheKey === item){
                this.cache = {}
            }
        })
    }

    getValue(cacheKey:string){
        this.loadingThree = true;
        this.mainService.getValue(this.selectCacheKey, cacheKey).subscribe(res=>{
            this.cache = res.data;
        }).add(()=>{this.loadingThree = false})
    }
}
